import React, { useEffect, useState } from 'react';
import {
  Card,
  Descriptions,
  Avatar,
  Button,
  Upload,
  message,
  Space,
  Comment,
  Rate,
  Input,
} from 'antd';
import { UserOutlined, UploadOutlined } from '@ant-design/icons';

const { TextArea } = Input;

const PersonalInfo = () => {
  const [avatarUrl, setAvatarUrl] = useState('');
  const [rating, setRating] = useState(0);
  const [comment, setComment] = useState('');
  const [username, setUsername] = useState(
    localStorage.getItem('username') || '用户名未知'
  );
  const [email, setEmail] = useState(
    localStorage.getItem('email') || '邮箱未知'
  );
  const [signature, setSignature] = useState(
    localStorage.getItem('signature') || '个性签名未知'
  );
  const [identity, setIdentity] = useState(
    localStorage.getItem('identity') || '学校/公司未知'
  );
  const handleChange = async info => {
    if (info.file.status === 'uploading') {
      // 获取 token
      const token = sessionStorage.getItem('token');

      // 创建一个 FormData 对象
      const formData = new FormData();
      formData.append('file', info.file.originFileObj);
      formData.append('token', token);

      // 发送请求
      try {
        const response = await fetch('http://localhost:29157/api/users/head', {
          method: 'POST',
          body: formData,
        });

        // 处理响应
        if (response.ok) {
          const data = await response.json();
          if (data.status) {
            message.success(`${info.file.name} 上传成功`);
            localStorage.setItem(
              'headSculptureUrl',
              data.data.headSculptureUrl
            );
            setAvatarUrl(data.data.headSculptureUrl);
          } else {
            message.error(`${info.file.name} 上传失败：${data.error}`);
          }
        } else {
          message.error(`${info.file.name} 上传失败：${response.statusText}`);
        }
      } catch (error) {
        message.error(`${info.file.name} 上传失败：${error.message}`);
      }
    }
  };

  useEffect(() => {
    setUsername(localStorage.getItem('username') || '用户名未知');
    setEmail(localStorage.getItem('email') || '邮箱未知');
    setSignature(localStorage.getItem('signature') || '个性签名未知');
    setIdentity(localStorage.getItem('identity') || '学校/公司未知');
    setAvatarUrl(localStorage.getItem('headSculptureUrl') || '');
  }, []);

  useEffect(() => {
    console.log(avatarUrl);
  }, [avatarUrl]);
  const dummyRequest = ({ file, onSuccess }) => {
    setTimeout(() => {
      onSuccess('ok');
    }, 0);
  };

  const handleSubmit = () => {
    message.success('感谢您的反馈！');
    setRating(0);
    setComment('');
  };

  return (
    <div
      style={{
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        minHeight: '100vh',
        backgroundColor: '#f0f2f5',
      }}>
      <Card
        style={{
          maxWidth: 800,
          borderRadius: 12,
          boxShadow: '0 6px 12px rgba(0, 0, 0, 0.1)',
          marginBottom: 16,
        }}>
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            marginBottom: 16,
          }}>
          <Avatar
            size={100}
            icon={<UserOutlined />}
            src={avatarUrl}
            alt='用户头像'
          />
          <Upload
            customRequest={dummyRequest}
            showUploadList={false}
            onChange={handleChange}>
            <Button icon={<UploadOutlined />}>修改头像</Button>
          </Upload>
        </div>
        <Descriptions column={1}>
          <Descriptions.Item label='用户名'>{username}</Descriptions.Item>
          <Descriptions.Item label='邮箱'>{email}</Descriptions.Item>
          <Descriptions.Item label='个性签名'>{signature}</Descriptions.Item>
          <Descriptions.Item label='学校/公司'>{identity}</Descriptions.Item>
        </Descriptions>
        <Space>
          <Button
            type='primary'
            onClick={() => message.info('修改信息功能尚未实现')}>
            修改信息
          </Button>
          <Button
            type='ghost'
            onClick={() => message.info('退出登录功能尚未实现')}>
            退出登录
          </Button>
        </Space>
        <Comment
          author={<span>赵文博</span>}
          avatar={
            <Avatar
              icon={<UserOutlined />}
              src={avatarUrl}
              alt='用户头像'
            />
          }
          content={
            <div>
              <Rate
                value={rating}
                onChange={setRating}
              />
              <TextArea
                value={comment}
                onChange={e => setComment(e.target.value)}
                placeholder='请留下宝贵建议'
                autoSize={{ minRows: 4, maxRows: 8 }}
                style={{ marginTop: 12 }}
              />
            </div>
          }
        />
        <div
          style={{
            display: 'flex',
            justifyContent: 'flex-end',
            marginTop: 12,
          }}>
          <Button
            type='primary'
            onClick={handleSubmit}>
            提交反馈
          </Button>
        </div>
      </Card>
    </div>
  );
};

export default PersonalInfo;
